import { Context, Next } from 'koa'
import env from '../../env'

export default async (ctx: Context, next: Next) => {
	ctx.set('Access-Control-Allow-Headers', 'Content-Type, token')
	ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
	if (env.envType === 'dev') {
		ctx.set('Access-Control-Allow-Origin', '*')
		ctx.method == 'OPTIONS' ? (ctx.body = 200) : await next()
	} else {
		const crossWhiteList = [
			//
			`https://${env.DOMAIN_NAME}`,
			`https://ipv6.${env.DOMAIN_NAME}:${env.IPV6_PROT}`
		]
		const orgin = ctx.header.origin + ''
		if (crossWhiteList.includes(orgin)) {
			ctx.set('Access-Control-Allow-Origin', orgin)
		}
		return next()
	}
}
